import sys
import os
from PyQt6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, 
                             QPushButton, QProgressBar, QListWidget, 
                             QFileDialog, QLabel, QSizePolicy, QDialog,
                             QFormLayout, QLineEdit, QComboBox)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon
from openpyxl import Workbook, load_workbook 

class SettingsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("系统设置")
        self.setFixedSize(400, 300)
        
        layout = QVBoxLayout()
        
        # 设置表单
        form_layout = QFormLayout()
        
        self.server_input = QLineEdit()
        self.server_input.setPlaceholderText("请输入服务器地址")
        form_layout.addRow("服务器地址:", self.server_input)
        
        self.theme_combo = QComboBox()
        self.theme_combo.addItems(["默认主题", "深色主题", "蓝色主题"])
        form_layout.addRow("界面主题:", self.theme_combo)
        
        layout.addLayout(form_layout)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        self.save_btn = QPushButton("保存设置")
        self.save_btn.clicked.connect(self.accept)
        btn_layout.addWidget(self.save_btn)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        btn_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(btn_layout)
        self.setLayout(layout)
        
        self.setStyleSheet("""
            QDialog {
                background-color: #f5f5f5;
            }
            QLabel {
                font-size: 14px;
            }
            QLineEdit, QComboBox {
                padding: 5px;
                font-size: 14px;
                border: 1px solid #ddd;
                border-radius: 3px;
            }
        """)

class ExcelProcessor(QWidget):
    def __init__(self):
        super().__init__()
        # 设置无边框窗口
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        
        self.setWindowTitle("附属医院月度算薪")
        self.setGeometry(100, 100, 800, 600)
        self.setWindowIcon(QIcon("icon.png"))
        
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 顶部工具栏（包含标题和按钮）
        top_toolbar = QHBoxLayout()
        top_toolbar.setContentsMargins(0, 0, 0, 10)
        
        # 添加标题
        title_label = QLabel("附属医院月度算薪系统")
        title_label.setStyleSheet("font-size: 16px; font-weight: bold;")
        top_toolbar.addWidget(title_label)
        
        # 添加弹簧使按钮靠右
        top_toolbar.addStretch()
        
        # 添加设置按钮
        self.settings_btn = QPushButton("⚙")  # 使用齿轮符号
        self.settings_btn.setFixedSize(30, 30)
        self.settings_btn.setStyleSheet("""
            QPushButton {
                background-color: #2196F3;
                color: white;
                border-radius: 15px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #64b5f6;
            }
        """)
        self.settings_btn.clicked.connect(self.show_settings)
        top_toolbar.addWidget(self.settings_btn)
        
        # 添加关闭按钮（右侧）
        self.close_btn = QPushButton("×")
        self.close_btn.setFixedSize(30, 30)
        self.close_btn.setStyleSheet("""
            QPushButton {
                background-color: #ff4d4d;
                color: white;
                border-radius: 15px;
                font-size: 18px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #ff6666;
            }
        """)
        self.close_btn.clicked.connect(self.close)
        top_toolbar.addWidget(self.close_btn)
        
        main_layout.addLayout(top_toolbar)
        
        # 文件选择区域
        file_group = self.create_file_group()
        main_layout.addLayout(file_group)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self.progress_bar.setFixedHeight(30)
        main_layout.addWidget(self.progress_bar)
        
        # 列表显示
        self.list_widget = QListWidget()
        self.list_widget.setMinimumHeight(300)
        main_layout.addWidget(self.list_widget)
        
        # 底部按钮
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 10, 0, 0)
        
        self.process_btn = QPushButton("开始处理")
        self.process_btn.setFixedSize(150, 40)
        self.process_btn.clicked.connect(self.process_files)
        button_layout.addWidget(self.process_btn)
        
        button_layout.addSpacing(20)  # 添加间距
        
        self.clear_btn = QPushButton("清空列表")
        self.clear_btn.setFixedSize(150, 40)
        self.clear_btn.clicked.connect(self.clear_list)
        button_layout.addWidget(self.clear_btn)
        
        main_layout.addLayout(button_layout)
        
        self.setLayout(main_layout)
        self.setStyleSheet(self.get_stylesheet())
        
        # 窗口拖动相关变量
        self.drag_start_position = None
        self.folder_path = ""  # 初始化文件夹路径
    
    def show_settings(self):
        """显示设置对话框"""
        settings_dialog = SettingsDialog(self)
        if settings_dialog.exec() == QDialog.DialogCode.Accepted:
            self.list_widget.addItem("设置已保存")
    
    def create_file_group(self):
        group_layout = QVBoxLayout()
        group_layout.setSpacing(15)
        
        # 文件选择
        file_btn_layout = QHBoxLayout()
        self.file_label = QLabel("未选择文件")
        self.file_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        self.file_btn = QPushButton("选择Excel文件")
        self.file_btn.setFixedSize(150, 40)
        self.file_btn.clicked.connect(self.select_file)
        file_btn_layout.addWidget(self.file_btn)
        file_btn_layout.addWidget(self.file_label)
        
        # 文件夹选择
        folder_btn_layout = QHBoxLayout()
        self.folder_label = QLabel("未选择文件夹")
        self.folder_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        self.folder_btn = QPushButton("选择输出文件夹")
        self.folder_btn.setFixedSize(150, 40)
        self.folder_btn.clicked.connect(self.select_folder)
        folder_btn_layout.addWidget(self.folder_btn)
        folder_btn_layout.addWidget(self.folder_label)
        
        group_layout.addLayout(file_btn_layout)
        group_layout.addLayout(folder_btn_layout)
        
        return group_layout
    
    def select_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, 
            "选择Excel文件", 
            "", 
            "Excel文件 (*.xlsx *.xls)"
        )
        if file_path:
            self.file_label.setText(file_path.split('/')[-1])
            self.list_widget.addItem(f"已选择文件: {file_path}")
    
    def select_folder(self):
        folder_path = QFileDialog.getExistingDirectory(
            self,
            "选择输出文件夹"
        )
        if folder_path:
            self.folder_path = folder_path  # 保存文件夹路径
            self.folder_label.setText(folder_path)
            self.list_widget.addItem(f"输出目录: {folder_path}")
    
    def process_files(self):
        self.progress_bar.setValue(0)
        self.list_widget.addItem("开始处理文件...")
        
        # 检查是否已选择输出文件夹
        if not self.folder_path:
            self.list_widget.addItem("错误：请先选择输出文件夹")
            self.progress_bar.setValue(0)
            return
            
        try:
            # 创建新的工作簿
            wb = Workbook()
            ws = wb.active
            
            # 设置表头
            headers = [
                "考勤科室", "姓名", "请假天数", "出勤天数", 
                "晚班天数", "晚班金额（元）", 
                "周末、节假日值班天数", "值班金额（元）", 
                "休假类型", "休假天数","20%绩效"
            ]
            
            # 写入表头
            for col, header in enumerate(headers, 1):
                ws.cell(row=1, column=col, value=header)
            
            # 在选择的文件夹下创建考勤统计子文件夹
            output_folder = os.path.join(self.folder_path, "考勤统计")
            try:
                os.makedirs(output_folder, exist_ok=True)
                self.list_widget.addItem(f"已创建考勤统计文件夹: {output_folder}")
            except Exception as e:
                self.list_widget.addItem(f"创建文件夹出错: {str(e)}")
                self.progress_bar.setValue(0)
                return
            
            # 保存主文件路径
            master_file = os.path.join(output_folder, "考勤统计.xlsx")
            wb.save(master_file)
            self.list_widget.addItem(f"已创建考勤表格模板: {master_file}")
        except Exception as e:
            self.list_widget.addItem(f"错误：{str(e)}")
            self.progress_bar.setValue(0)
            return   
            # 遍历文件夹中的Excel文件并合并数据
        self.list_widget.addItem("开始合并数据...")
        processed_files = 0
        
        for file in os.listdir(self.folder_path):
            if file.endswith(('.xls', '.xlsx')) and file != "考勤统计.xlsx":
                file_path = os.path.join(self.folder_path, file)
                try:
                    src_wb = load_workbook(file_path)
                    src_ws = src_wb.active
                    
                    # 检查表头是否匹配（比较第二行与主文件第一行）
                    match_count = 0
                    for col in range(1, len(headers)+1):
                        src_value = str(src_ws.cell(row=2, column=col).value or "")
                        master_value = str(headers[col-1] or "")
                        if src_value.strip() == master_value.strip():
                            match_count += 1
                    
                    # 如果匹配的列数不足80%，则跳过该文件
                    if match_count / len(headers) < 0.2:
                        self.list_widget.addItem(f"跳过文件 {file}: 表头匹配度不足 (匹配{match_count}/{len(headers)}列)")
                        continue
                        
                    # 从第3行开始读取数据（因为第二行是表头）
                    for row in range(3, src_ws.max_row + 1):
                        # 检查是否空行
                        if not any(src_ws.cell(row=row, column=col).value for col in range(1, len(headers)+1)):
                            continue
                            
                        # 获取当前主文件的最新行号
                        current_row = ws.max_row + 1
                        
                        # 复制整行数据到主文件
                        for col in range(1, len(headers)+1):
                            ws.cell(row=current_row, column=col, value=src_ws.cell(row=row, column=col).value)
                    
                    processed_files += 1
                    self.list_widget.addItem(f"已合并文件: {file} (匹配{match_count}/{len(headers)}列)")
                    
                except Exception as e:
                    self.list_widget.addItem(f"处理文件 {file} 出错: {str(e)}")
        
        # 保存合并后的数据
        if processed_files > 0:
            wb.save(master_file)
            self.list_widget.addItem(f"成功合并 {processed_files} 个文件的数据")
        else:
            self.list_widget.addItem("未找到可合并的Excel文件")
 

    def clear_list(self):
        self.list_widget.clear()
        self.file_label.setText("未选择文件")
        self.folder_label.setText("未选择文件夹")
        self.progress_bar.setValue(0)
        self.folder_path = ""  # 清空文件夹路径
    
    def mousePressEvent(self, event):
        """实现窗口拖动功能"""
        if event.button() == Qt.MouseButton.LeftButton:
            self.drag_start_position = event.globalPosition().toPoint()
    
    def mouseMoveEvent(self, event):
        """实现窗口拖动功能"""
        if hasattr(self, 'drag_start_position') and self.drag_start_position:
            delta = event.globalPosition().toPoint() - self.drag_start_position
            self.move(self.pos() + delta)
            self.drag_start_position = event.globalPosition().toPoint()
    
    def mouseReleaseEvent(self, event):
        """清除拖动状态"""
        if hasattr(self, 'drag_start_position'):
            self.drag_start_position = None
    
    def get_stylesheet(self):
        return """
            QWidget {
                background-color: #f5f5f5;
                font-family: 'Microsoft YaHei';
            }
            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 5px;
                padding: 8px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
            QLabel {
                font-size: 14px;
                color: #333;
                padding: 5px;
            }
            QProgressBar {
                border: 1px solid #ccc;
                border-radius: 5px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #4CAF50;
                width: 10px;
            }
            QListWidget {
                background-color: white;
                border: 1px solid #ddd;
                border-radius: 5px;
                padding: 10px;
                font-size: 14px;
            }
        """

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ExcelProcessor()
    window.show()
    sys.exit(app.exec())
